<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 5.4.2">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"xiaoqingming18.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.15.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="异常引发我们肯定见过堆栈轨迹，也就是程序执行过程中某个特定点上挂起的方法调用列表。当程序因为未捕获的异常而终止时，就会显示堆栈轨迹。异常会因为程序本身或者错误的操作等情况引发，这会导致操作无法完成或者数据丢失等不良后果。为了避免异常带来的不良后果，程序应该在异常发生时保证：  向用户通知错误； 让用户返回到一种安全状态，让用户执行其他的命令； 允许用户保存工作结果，以妥善的方式终止程序。  异常处">
<meta property="og:type" content="article">
<meta property="og:title" content="Java：异常类与捕获异常">
<meta property="og:url" content="http://xiaoqingming18.github.io/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/index.html">
<meta property="og:site_name" content="鸣蜩十七">
<meta property="og:description" content="异常引发我们肯定见过堆栈轨迹，也就是程序执行过程中某个特定点上挂起的方法调用列表。当程序因为未捕获的异常而终止时，就会显示堆栈轨迹。异常会因为程序本身或者错误的操作等情况引发，这会导致操作无法完成或者数据丢失等不良后果。为了避免异常带来的不良后果，程序应该在异常发生时保证：  向用户通知错误； 让用户返回到一种安全状态，让用户执行其他的命令； 允许用户保存工作结果，以妥善的方式终止程序。  异常处">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://xiaoqingming18.github.io/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/异常类.png">
<meta property="article:published_time" content="2023-04-28T02:58:16.000Z">
<meta property="article:modified_time" content="2023-06-15T05:37:06.183Z">
<meta property="article:author" content="鸣蜩十七">
<meta property="article:tag" content="-Java基础 -Java异常">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://xiaoqingming18.github.io/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/异常类.png">


<link rel="canonical" href="http://xiaoqingming18.github.io/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://xiaoqingming18.github.io/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/","path":"2023/04/28/java：异常类与捕获异常/","title":"Java：异常类与捕获异常"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Java：异常类与捕获异常 | 鸣蜩十七</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">鸣蜩十七</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">鸣蜩十七是和女朋友谈恋爱的日子</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-schedule"><a href="/schedule/" rel="section"><i class="fa fa-calendar fa-fw"></i>日程表</a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li><li class="menu-item menu-item-commonweal"><a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
  </ul>
</nav>




</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8%E5%BC%95%E5%8F%91"><span class="nav-text">异常引发</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8%E7%B1%BB"><span class="nav-text">异常类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A3%B0%E6%98%8E%E5%BC%82%E5%B8%B8"><span class="nav-text">声明异常</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%8A%9B%E5%87%BA%E5%BC%82%E5%B8%B8"><span class="nav-text">抛出异常</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%BC%82%E5%B8%B8%E7%B1%BB"><span class="nav-text">创建异常类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8"><span class="nav-text">捕获异常</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#try-catch%E5%AD%90%E5%8F%A5"><span class="nav-text">try&#x2F;catch子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8D%95%E8%8E%B7%E5%A4%9A%E4%B8%AA%E5%BC%82%E5%B8%B8"><span class="nav-text">捕获多个异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8%E9%93%BE%E6%9D%A1"><span class="nav-text">异常链条</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#final%E5%AD%90%E5%8F%A5"><span class="nav-text">final子句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#try-with-Resources-%E8%AF%AD%E5%8F%A5"><span class="nav-text">try-with-Resources 语句</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">鸣蜩十七</p>
  <div class="site-description" itemprop="description">记录我的学习、生活和恋爱日常</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xiaoqingming18.github.io/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="鸣蜩十七">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="鸣蜩十七">
      <meta itemprop="description" content="记录我的学习、生活和恋爱日常">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Java：异常类与捕获异常 | 鸣蜩十七">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java：异常类与捕获异常
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-04-28 10:58:16" itemprop="dateCreated datePublished" datetime="2023-04-28T10:58:16+08:00">2023-04-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-06-15 13:37:06" itemprop="dateModified" datetime="2023-06-15T13:37:06+08:00">2023-06-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">-后端</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="异常引发"><a href="#异常引发" class="headerlink" title="异常引发"></a>异常引发</h1><p>我们肯定见过<strong>堆栈轨迹</strong>，也就是程序执行过程中某个特定点上挂起的方法调用列表。当程序因为未捕获的异常而终止时，就会显示堆栈轨迹。异常会因为程序本身或者错误的操作等情况引发，这会导致操作无法完成或者数据丢失等不良后果。为了避免异常带来的不良后果，程序应该在异常发生时保证：</p>
<ol>
<li>向用户通知错误；</li>
<li>让用户返回到一种安全状态，让用户执行其他的命令；</li>
<li>允许用户保存工作结果，以妥善的方式终止程序。</li>
</ol>
<p>异常处理的任务就是将控制权从产生异常的地方，转移到能够处理异常的异常处理器。异常处理通常需要考虑：</p>
<ol>
<li><strong>用户输入错误</strong>，当需要用户进行输入时，用户可能不会按照程序的要求来输入；</li>
<li><strong>设备错误</strong>，程序调用的硬件出现问题；</li>
<li><strong>物理限制</strong>，例如程序所需的存储空间耗尽；</li>
<li><strong>代码错误</strong>，程序有的方法编写错误，引发异常。</li>
</ol>
<p>传统的方式是返回一个特殊的错误码，方法根据错误码进行分析。或者是返回 null 引用，但无论是空引用和错误码，这些都是程序编写中可能会使用的值。因此在很多情况下，方法并不返回任何值，而是抛出一个封装了错误信息的对象。</p>
<h1 id="异常类"><a href="#异常类" class="headerlink" title="异常类"></a>异常类</h1><p>异常对象都派生自<code>Throwable</code>类的一个实例，所有异常都继承<code>Throwable</code>类而来。==<code>Throwable</code>类分为<code>Error</code>类和<code>Exception</code>类==，<code>Error</code>类表示程序运行时系统出现的严重错误，通常是无法恢复的，捕获和处理这类异常没有意义，所以==<code>Error</code>类异常不需要我们操心==。<code>Exception</code> 类又扩展为两个类：<code>IOException</code> 和 <code>RuntimeException</code>。<code>IOException</code>类的错误与程序本身没有关系，==我们只需要考虑<code>Exception</code> 类的异常==。所以，<strong>如果出现<code>RuntimeException</code>异常，一定是程序员本身的问题</strong>。</p>
<p><img src="/2023/04/28/java%EF%BC%9A%E5%BC%82%E5%B8%B8%E7%B1%BB%E4%B8%8E%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8/异常类.png" alt="异常类派生图"></p>
<p>派生于 <code>Error</code>类和<code>RuntimeException</code>类的所有异常为<strong>非检查型</strong>异常，其他所有异常为<strong>检查型</strong>异常。</p>
<h1 id="声明异常"><a href="#声明异常" class="headerlink" title="声明异常"></a>声明异常</h1><p>当调用某个方法发生异常时，这个方法需要抛出发生的异常，编译器才知道程序出现了何种异常，系统才能搜索处理对应异常的<strong>异常处理器</strong>。</p>
<p>我们要在方法声明中使用<code>throws</code>关键字来声明方法可能抛出的异常类型：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">afunction</span><span class="params">()</span> <span class="keyword">throws</span> aException {···}</span><br></pre></td></tr></tbody></table></figure>
<p>如果一个方法可能会抛出多个异常，我们需要声明所有异常，用逗号隔开这些异常：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">afuncion</span><span class="params">()</span> <span class="keyword">throws</span> aException,anotherException {···}</span><br></pre></td></tr></tbody></table></figure>
<p>Error 和 RuntimeException 的非检查型异常都不需要被声明，因为这是程序员一开始就需要避免的事情。因此一个方法需要声明所有可能抛出的检查型异常，而不是非检查型。</p>
<h1 id="抛出异常"><a href="#抛出异常" class="headerlink" title="抛出异常"></a>抛出异常</h1><p>在程序执行过程中，使用 throw 关键字将一个异常对象抛出，使程序进入异常处理流程。抛出异常通常用于表示程序在执行过程中遇到了无法处理的异常情况，例如文件读写失败、网络连接中断等。</p>
<p>要注意的是，一旦异常被抛出，方法就不会返回到它的调用者。</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">ExceptionName</span>()</span><br></pre></td></tr></tbody></table></figure>
<p>下面来看一个例子：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="type">int</span> <span class="title function_">divide</span><span class="params">(<span class="type">int</span> a, <span class="type">int</span> b)</span> <span class="keyword">throws</span> ArithmeticException {</span><br><span class="line">        <span class="keyword">if</span> (b == <span class="number">0</span>) {</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">ArithmeticException</span>(<span class="string">"除数不能是0！"</span>);</span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">return</span> a / b;</span><br><span class="line">    }</span><br></pre></td></tr></tbody></table></figure>
<p>在上面的<code>divide</code>方法中，如果除数是0，就抛出异常，若不是0就正常返回<code>a/b</code>。</p>
<p>异常类中可能有自带一个字符串参数的构造器，通过这个构造器可以给出异常的描述信息。例<code>IllegalArgumentException</code>异常可以通过它的构造器附带说明信息：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalArgumentException</span>(<span class="string">"这是个不合法的参数异常"</span>);</span><br></pre></td></tr></tbody></table></figure>
<h1 id="创建异常类"><a href="#创建异常类" class="headerlink" title="创建异常类"></a>创建异常类</h1><p>程序可能遇到某种特殊的异常，这种异常用现有的异常类可能很难描述，此时可以自定义一个异常类。自定义的异常类派生于<code>Excpetion</code>类或者<code>Excpetion</code>类的某个子类，自定义的类应该包括默认构造器和包含详细描述信息的构造器。例如：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">FileFormatException</span> <span class="keyword">extends</span> <span class="title class_">IOException</span></span><br><span class="line">{</span><br><span class="line">      <span class="keyword">public</span> <span class="title function_">FileFormatException</span><span class="params">()</span> {}</span><br><span class="line">      <span class="keyword">public</span> <span class="title function_">FileFormatException</span><span class="params">(String message)</span> {</span><br><span class="line">            <span class="built_in">super</span>(message);</span><br><span class="line">      }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>
<p>自定义异常类之后，就可以在方法中声明异常并在方法中抛出。</p>
<p>==注意，<code>message</code>字段不用再自定义的异常类中添加，只需要调用<code>super()</code>构造器将其传到<code>Exception</code>类即可==。</p>
<h1 id="捕获异常"><a href="#捕获异常" class="headerlink" title="捕获异常"></a>捕获异常</h1><p>上面说到了抛出异常，如果只抛出异常而不捕获异常，程序就会终止，正确的做法是抛出异常后并捕获异常，提供异常处理办法。</p>
<h2 id="try-catch子句"><a href="#try-catch子句" class="headerlink" title="try/catch子句"></a>try/catch子句</h2><p>使用 try 和 catch 关键字可以捕获异常，try/catch 语句块应该被放置在可能产生异常的地方，使用 try/catch 的语法如下：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>{</span><br><span class="line">   <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(ExceptionName e){</span><br><span class="line">   <span class="comment">//code</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>
<p>如果 try 语句中的任何代码抛出了 catch 子句指定的一个异常类，则程序会跳过 try 语句块的剩余代码，转去执行 catch 子句中的处理器代码。如果 try 语句块的代码没有抛出任何异常，则 catch 子句的代码会被自动跳过。==如果方法抛出了 catch 子句中没有声明的一个异常类型，这个方法就会自动退出==。</p>
<h2 id="捕获多个异常"><a href="#捕获多个异常" class="headerlink" title="捕获多个异常"></a>捕获多个异常</h2><p>一个 try 代码块后面可以跟随多个 catch 代码块，对每个异常类型都用一个单独的 catch 子句来实现<strong>多个异常的捕获</strong>。</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>{</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(异常类型 <span class="number">1</span> 异常的变量名 <span class="number">1</span>){</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(异常类型 <span class="number">2</span> 异常的变量名 <span class="number">2</span>){</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(异常类型 <span class="number">3</span> 异常的变量名 <span class="number">3</span>){</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>
<p>同一个 catch 子句可以捕获多个异常，如果 2 种异常捕获后采取的解决办法是相同的，可以用<code>|</code>进行连接。</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>{</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(异常类型<span class="number">1</span> | 异常类型<span class="number">2</span> 异常的变量名){</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>
<h2 id="异常链条"><a href="#异常链条" class="headerlink" title="异常链条"></a>异常链条</h2><p>待补充</p>
<h2 id="final子句"><a href="#final子句" class="headerlink" title="final子句"></a>final子句</h2><p><code>finally</code>关键字用来创建在<code>try</code>代码块后面执行的代码块，无论是否发生异常，<code>finally</code>代码块中的代码总会被执行。在 <code>finally</code>代码块中，可以运行清理类型等收尾善后性质的语句。语法为：</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>{</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(异常类型 异常的变量名){</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">finally</span>{</span><br><span class="line">  <span class="comment">//code</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>
<p><code>try</code>语句可以只有<code>finally</code>子句，而忽略<code>catch</code>子句。不过<code>finally</code>子句也可能有异常，可以使用嵌套的<code>try</code>子句来捕获异常，这种方法不仅保险且功能更强。</p>
<figure class="highlight java"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>{</span><br><span class="line">      <span class="keyword">try</span>{</span><br><span class="line">            <span class="comment">//code</span></span><br><span class="line">      }</span><br><span class="line">      <span class="keyword">finally</span>{</span><br><span class="line">            <span class="comment">//code</span></span><br><span class="line">      }</span><br><span class="line">}</span><br><span class="line"><span class="keyword">catch</span>(异常类型 异常的变量名)</span><br><span class="line">{</span><br><span class="line">      <span class="comment">//code</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>
<h2 id="try-with-Resources-语句"><a href="#try-with-Resources-语句" class="headerlink" title="try-with-Resources 语句"></a>try-with-Resources 语句</h2><p>待补充（不考）</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java%E5%9F%BA%E7%A1%80-Java%E5%BC%82%E5%B8%B8/" rel="tag"># -Java基础 -Java异常</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/04/26/CSS%EF%BC%9A%E5%9D%97%E7%BA%A7%E5%85%83%E7%B4%A0%E5%8F%8A%E8%87%AA%E9%80%82%E5%BA%94%E5%B8%83%E5%B1%80/" rel="prev" title="CSS：块级元素细节">
                  <i class="fa fa-chevron-left"></i> CSS：块级元素细节
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/05/03/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%8E%9F%E7%90%86%EF%BC%9A%E8%A7%86%E5%9B%BE/" rel="next" title="数据库原理：视图">
                  数据库原理：视图 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">鸣蜩十七</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  




  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
